import { create } from 'zustand';
import { persist } from 'zustand/middleware';

// 支持的语言列表
export const SUPPORTED_LANGUAGES = {
  'zh-CN': '简体中文',
  'zh-TW': '繁體中文',
  en: 'English',
  ja: '日本語',
  ko: '한국어',
  fr: 'Français',
  de: 'Deutsch',
  es: 'Español',
  ru: 'Русский',
  pt: 'Português',
  it: 'Italiano',
  ar: 'العربية',
} as const;

export type SupportedLanguage = keyof typeof SUPPORTED_LANGUAGES;

// 翻译资源类型
export interface TranslationResource {
  [key: string]: string | string[] | TranslationResource;
}

// 翻译上下文
export interface TranslationContext {
  count?: number;
  gender?: 'male' | 'female' | 'other';
  [key: string]: any;
}

// 国际化状态
interface I18nState {
  currentLanguage: SupportedLanguage;
  fallbackLanguage: SupportedLanguage;
  resources: Record<SupportedLanguage, TranslationResource>;
  loading: boolean;
  error: string | null;

  // Actions
  setLanguage: (language: SupportedLanguage) => void;
  loadResources: (
    language: SupportedLanguage,
    resources: TranslationResource
  ) => void;
  setLoading: (loading: boolean) => void;
  setError: (error: string | null) => void;
}

// 创建国际化状态管理
export const useI18nStore = create<I18nState>()(
  persist(
    set => ({
      currentLanguage: 'zh-CN',
      fallbackLanguage: 'en',
      resources: {} as any,
      loading: false,
      error: null,

      setLanguage: language =>
        set(state => ({
          ...state,
          currentLanguage: language,
        })),

      loadResources: (language, resources) =>
        set(state => ({
          ...state,
          resources: {
            ...state.resources,
            [language]: resources,
          },
        })),

      setLoading: loading =>
        set(state => ({
          ...state,
          loading,
        })),

      setError: error =>
        set(state => ({
          ...state,
          error,
        })),
    }),
    {
      name: 'i18n-store',
      partialize: state => ({
        currentLanguage: state.currentLanguage,
        fallbackLanguage: state.fallbackLanguage,
      }),
    }
  )
);

// 翻译函数
export function useTranslation() {
  const { currentLanguage, fallbackLanguage, resources } = useI18nStore();

  const t = (key: string, context?: TranslationContext): string => {
    const currentResource = resources[currentLanguage];
    const fallbackResource = resources[fallbackLanguage];

    // 尝试从当前语言获取翻译
    let translation = getNestedValue(currentResource, key);

    // 如果当前语言没有，尝试从回退语言获取
    if (!translation && fallbackLanguage !== currentLanguage) {
      translation = getNestedValue(fallbackResource, key);
    }

    // 如果都没有，返回 key 本身
    if (!translation) {
      console.warn(`Translation missing for key: ${key}`);
      return key;
    }

    // 处理插值和复数
    return processTranslation(translation, context);
  };

  const changeLanguage = async (language: SupportedLanguage) => {
    const {
      setLanguage,
      setLoading,
      setError,
      loadResources,
      currentLanguage,
    } = useI18nStore.getState();

    // 如果已经是目标语言，直接返回
    if (currentLanguage === language) {
      return;
    }

    try {
      setLoading(true);
      setError(null);

      // 如果资源还没有加载，则加载它
      if (!resources[language]) {
        const resourceModule = await import(`./locales/${language}.json`);

        // 验证资源完整性
        const validation = validateLanguageResources(
          language,
          resourceModule.default
        );

        if (!validation.isValid) {
          console.warn(`Language ${language} validation failed:`, validation);
          // 仍然继续加载，但记录警告
        }

        if (validation.warnings.length > 0) {
          console.warn(`Language ${language} warnings:`, validation.warnings);
        }

        loadResources(language, resourceModule.default);
      }

      setLanguage(language);

      // 如果新语言不是英语，确保英语资源也已加载作为回退
      if (language !== 'en' && !resources['en']) {
        try {
          const fallbackModule = await import('./locales/en.json');
          loadResources('en', fallbackModule.default as any);
        } catch (error) {
          console.warn('Failed to load fallback language resources:', error);
        }
      }

      console.log(`Successfully changed language to: ${language}`);
    } catch (error) {
      console.error(`Failed to load language ${language}:`, error);
      setError(
        `Failed to load language ${language}: ${error instanceof Error ? error.message : String(error)}`
      );

      // 尝试回退到之前的语言
      if (currentLanguage !== language && resources[currentLanguage]) {
        console.warn(`Reverting to previous language: ${currentLanguage}`);
        setLanguage(currentLanguage);
      }

      throw error;
    } finally {
      setLoading(false);
    }
  };

  return {
    t,
    currentLanguage,
    changeLanguage,
    supportedLanguages: SUPPORTED_LANGUAGES,
  };
}

// 获取嵌套对象的值
function getNestedValue(
  obj: TranslationResource | undefined,
  path: string
): string | undefined {
  if (!obj) return undefined;

  const keys = path.split('.');
  let current: any = obj;

  for (const key of keys) {
    if (current && typeof current === 'object' && key in current) {
      current = current[key];
    } else {
      return undefined;
    }
  }

  return typeof current === 'string' ? current : undefined;
}

// 处理翻译字符串的插值和复数
function processTranslation(
  translation: string,
  context?: TranslationContext
): string {
  if (!context) return translation;

  let result = translation;

  // 处理插值 {{variable}}
  result = result.replace(/\{\{(\w+)\}\}/g, (match, key) => {
    return context[key]?.toString() || match;
  });

  // 处理复数形式
  if (context.count !== undefined) {
    result = handlePluralization(result, context.count);
  }

  return result;
}

// 处理复数形式
function handlePluralization(translation: string, count: number): string {
  // 简单的复数处理，支持 {count, plural, =0{zero} =1{one} other{other}} 格式
  const pluralRegex = /\{count,\s*plural,\s*(.+?)\}/g;

  return translation.replace(pluralRegex, (match, rules) => {
    const ruleMap: Record<string, string> = {};

    // 解析规则
    const ruleRegex = /(=\d+|zero|one|two|few|many|other)\{([^}]*)\}/g;
    let ruleMatch;

    while ((ruleMatch = ruleRegex.exec(rules)) !== null) {
      ruleMap[ruleMatch[1]] = ruleMatch[2];
    }

    // 选择合适的规则
    const exactMatch = `=${count}`;
    if (ruleMap[exactMatch]) {
      return ruleMap[exactMatch];
    }

    if (count === 0 && ruleMap.zero) {
      return ruleMap.zero;
    }

    if (count === 1 && ruleMap.one) {
      return ruleMap.one;
    }

    if (count === 2 && ruleMap.two) {
      return ruleMap.two;
    }

    return ruleMap.other || match;
  });
}

// 格式化数字
export function formatNumber(value: number, locale?: string): string {
  const { currentLanguage } = useI18nStore.getState();
  const targetLocale = locale || currentLanguage;

  return new Intl.NumberFormat(targetLocale).format(value);
}

// 格式化货币
export function formatCurrency(
  value: number,
  currency: string = 'USD',
  locale?: string
): string {
  const { currentLanguage } = useI18nStore.getState();
  const targetLocale = locale || currentLanguage;

  return new Intl.NumberFormat(targetLocale, {
    style: 'currency',
    currency,
  }).format(value);
}

// 格式化日期
export function formatDate(
  date: Date | string | number,
  options?: Intl.DateTimeFormatOptions,
  locale?: string
): string {
  const { currentLanguage } = useI18nStore.getState();
  const targetLocale = locale || currentLanguage;

  const dateObj =
    typeof date === 'string' || typeof date === 'number'
      ? new Date(date)
      : date;

  return new Intl.DateTimeFormat(targetLocale, options).format(dateObj);
}

// 格式化相对时间
export function formatRelativeTime(
  date: Date | string | number,
  locale?: string
): string {
  const { currentLanguage } = useI18nStore.getState();
  const targetLocale = locale || currentLanguage;

  const dateObj =
    typeof date === 'string' || typeof date === 'number'
      ? new Date(date)
      : date;
  const now = new Date();
  const diffInSeconds = Math.floor((now.getTime() - dateObj.getTime()) / 1000);

  const rtf = new Intl.RelativeTimeFormat(targetLocale, { numeric: 'auto' });

  if (Math.abs(diffInSeconds) < 60) {
    return rtf.format(-diffInSeconds, 'second');
  }

  const diffInMinutes = Math.floor(diffInSeconds / 60);
  if (Math.abs(diffInMinutes) < 60) {
    return rtf.format(-diffInMinutes, 'minute');
  }

  const diffInHours = Math.floor(diffInMinutes / 60);
  if (Math.abs(diffInHours) < 24) {
    return rtf.format(-diffInHours, 'hour');
  }

  const diffInDays = Math.floor(diffInHours / 24);
  if (Math.abs(diffInDays) < 30) {
    return rtf.format(-diffInDays, 'day');
  }

  const diffInMonths = Math.floor(diffInDays / 30);
  if (Math.abs(diffInMonths) < 12) {
    return rtf.format(-diffInMonths, 'month');
  }

  const diffInYears = Math.floor(diffInMonths / 12);
  return rtf.format(-diffInYears, 'year');
}

// 检测浏览器语言
export function detectBrowserLanguage(): SupportedLanguage {
  const browserLang = navigator.language || navigator.languages?.[0] || 'en';

  // 精确匹配
  if (browserLang in SUPPORTED_LANGUAGES) {
    return browserLang as SupportedLanguage;
  }

  // 语言代码匹配（如 zh-CN -> zh）
  const langCode = browserLang.split('-')[0];
  const matchedLang = Object.keys(SUPPORTED_LANGUAGES).find(lang =>
    lang.startsWith(langCode)
  );

  return (matchedLang as SupportedLanguage) || 'en';
}

// 初始化国际化
export async function initializeI18n(initialLanguage?: SupportedLanguage) {
  const { setLoading, setError, loadResources, currentLanguage, setLanguage } =
    useI18nStore.getState();

  try {
    setLoading(true);
    setError(null);

    // 使用最佳语言选择
    const targetLanguage = getBestLanguageChoice(
      initialLanguage || currentLanguage
    );

    // 如果传入了初始语言且与当前语言不同，更新当前语言
    if (initialLanguage && initialLanguage !== currentLanguage) {
      setLanguage(initialLanguage);
    }

    // 定义回退语言优先级
    const fallbackChain = [targetLanguage, 'en', 'zh-CN'];
    const uniqueFallbacks = [...new Set(fallbackChain)];

    let loadedSuccessfully = false;
    let lastError: any = null;

    // 尝试按优先级加载语言资源
    for (const lang of uniqueFallbacks) {
      try {
        const resourceModule = await import(`./locales/${lang}.json`);

        // 验证资源文件的完整性
        if (
          !resourceModule.default ||
          typeof resourceModule.default !== 'object'
        ) {
          throw new Error(`Invalid language resource format for ${lang}`);
        }

        // 检查必需的键是否存在
        const requiredKeys = ['common', 'nav', 'app'];
        const missingKeys = requiredKeys.filter(
          key => !resourceModule.default[key]
        );

        if (missingKeys.length > 0) {
          console.warn(
            `Language ${lang} missing required keys: ${missingKeys.join(', ')}`
          );
          // 继续使用，但记录警告
        }

        loadResources(lang as SupportedLanguage, resourceModule.default as any);

        // 如果这不是目标语言，更新当前语言
        if (lang !== targetLanguage) {
          setLanguage(lang as SupportedLanguage);
          console.warn(
            `Fell back to language: ${lang} (requested: ${targetLanguage})`
          );
        }

        loadedSuccessfully = true;
        break;
      } catch (error) {
        console.warn(`Failed to load language ${lang}:`, error);
        lastError = error;
        continue;
      }
    }

    if (!loadedSuccessfully) {
      throw new Error(
        `Failed to load any language resources. Last error: ${lastError}`
      );
    }

    // 尝试加载英语作为回退（如果还没有加载）
    const { resources } = useI18nStore.getState();
    if (!resources['en'] && targetLanguage !== 'en') {
      try {
        const fallbackModule = await import('./locales/en.json');
        loadResources('en', fallbackModule.default as any);
      } catch (error) {
        console.warn('Failed to load English fallback resources:', error);
      }
    }
  } catch (error) {
    console.error('Failed to initialize i18n:', error);
    setError(
      `Failed to initialize internationalization: ${error instanceof Error ? error.message : String(error)}`
    );

    // 最后的回退：使用硬编码的基本翻译
    const basicTranslations = {
      common: {
        ok: 'OK',
        cancel: 'Cancel',
        error: 'Error',
        loading: 'Loading...',
      },
      nav: {
        home: 'Home',
        settings: 'Settings',
      },
      app: {
        title: 'Tauri Modern Template',
      },
    };

    loadResources('en', basicTranslations);
    setLanguage('en');
    console.warn('Using basic hardcoded translations as final fallback');
  } finally {
    setLoading(false);
  }
}

// 导出常用的翻译键
export const COMMON_KEYS = {
  // 通用
  COMMON: {
    OK: 'common.ok',
    CANCEL: 'common.cancel',
    SAVE: 'common.save',
    DELETE: 'common.delete',
    EDIT: 'common.edit',
    ADD: 'common.add',
    REMOVE: 'common.remove',
    CLOSE: 'common.close',
    BACK: 'common.back',
    NEXT: 'common.next',
    PREVIOUS: 'common.previous',
    LOADING: 'common.loading',
    ERROR: 'common.error',
    SUCCESS: 'common.success',
    WARNING: 'common.warning',
    INFO: 'common.info',
  },

  // 导航
  NAV: {
    HOME: 'nav.home',
    SETTINGS: 'nav.settings',
    ABOUT: 'nav.about',
    HELP: 'nav.help',
  },

  // 设置
  SETTINGS: {
    TITLE: 'settings.title',
    LANGUAGE: 'settings.language',
    THEME: 'settings.theme',
    NOTIFICATIONS: 'settings.notifications',
    AUTO_START: 'settings.autoStart',
  },

  // 错误消息
  ERRORS: {
    NETWORK: 'errors.network',
    FILE_NOT_FOUND: 'errors.fileNotFound',
    PERMISSION_DENIED: 'errors.permissionDenied',
    UNKNOWN: 'errors.unknown',
  },
} as const;

// 检测系统语言
export function detectSystemLanguage(): SupportedLanguage {
  try {
    // 尝试从浏览器获取语言设置
    const browserLang = navigator.language || navigator.languages?.[0] || 'en';

    // 标准化语言代码
    const normalizedLang = browserLang.toLowerCase();

    // 检查是否直接匹配支持的语言
    for (const [code] of Object.entries(SUPPORTED_LANGUAGES)) {
      if (normalizedLang === code.toLowerCase()) {
        return code as SupportedLanguage;
      }
    }

    // 检查语言前缀匹配（例如 'en-US' -> 'en'）
    const langPrefix = normalizedLang.split('-')[0];
    for (const [code] of Object.entries(SUPPORTED_LANGUAGES)) {
      if (langPrefix === code.toLowerCase().split('-')[0]) {
        return code as SupportedLanguage;
      }
    }

    // 特殊处理中文
    if (langPrefix === 'zh') {
      // 根据地区代码决定简体还是繁体
      if (
        normalizedLang.includes('tw') ||
        normalizedLang.includes('hk') ||
        normalizedLang.includes('mo')
      ) {
        return 'zh-TW';
      }
      return 'zh-CN';
    }

    console.log(
      `System language ${browserLang} not supported, falling back to English`
    );
    return 'en';
  } catch (error) {
    console.warn('Failed to detect system language:', error);
    return 'en';
  }
}

// 获取最佳语言选择
export function getBestLanguageChoice(
  preferredLanguage?: string
): SupportedLanguage {
  // 1. 使用明确指定的语言
  if (
    preferredLanguage &&
    Object.keys(SUPPORTED_LANGUAGES).includes(preferredLanguage)
  ) {
    return preferredLanguage as SupportedLanguage;
  }

  // 2. 尝试检测系统语言
  const systemLang = detectSystemLanguage();
  if (systemLang) {
    return systemLang;
  }

  // 3. 默认使用英语
  return 'en';
}

// 语言健康检查
export function validateLanguageResources(
  _language: SupportedLanguage,
  resources: any
): {
  isValid: boolean;
  missingKeys: string[];
  warnings: string[];
} {
  const requiredKeys = [
    'common.ok',
    'common.cancel',
    'common.save',
    'common.loading',
    'nav.home',
    'nav.settings',
    'app.title',
    'settings.title',
  ];

  const missingKeys: string[] = [];
  const warnings: string[] = [];

  for (const keyPath of requiredKeys) {
    const keys = keyPath.split('.');
    let current = resources;
    let found = true;

    for (const key of keys) {
      if (!current || typeof current !== 'object' || !current[key]) {
        found = false;
        break;
      }
      current = current[key];
    }

    if (!found) {
      missingKeys.push(keyPath);
    }
  }

  // 检查资源的基本结构
  if (!resources.common) warnings.push('Missing "common" section');
  if (!resources.nav) warnings.push('Missing "nav" section');
  if (!resources.app) warnings.push('Missing "app" section');

  return {
    isValid: missingKeys.length === 0,
    missingKeys,
    warnings,
  };
}

// 语言系统诊断
export function diagnoseLanguageSystem(): {
  currentLanguage: SupportedLanguage;
  availableLanguages: string[];
  loadedResources: string[];
  errors: string[];
  recommendations: string[];
} {
  const { currentLanguage, resources, error } = useI18nStore.getState();
  const availableLanguages = Object.keys(SUPPORTED_LANGUAGES);
  const loadedResources = Object.keys(resources);
  const errors: string[] = [];
  const recommendations: string[] = [];

  // 检查当前语言是否有效
  if (!availableLanguages.includes(currentLanguage)) {
    errors.push(
      `Current language "${currentLanguage}" is not in supported languages list`
    );
  }

  // 检查当前语言资源是否已加载
  if (!loadedResources.includes(currentLanguage)) {
    errors.push(
      `Resources for current language "${currentLanguage}" are not loaded`
    );
  }

  // 检查是否有错误状态
  if (error) {
    errors.push(`I18n system error: ${error}`);
  }

  // 检查英语回退是否可用
  if (!loadedResources.includes('en') && currentLanguage !== 'en') {
    recommendations.push('Load English resources as fallback');
  }

  // 检查资源完整性
  if (resources[currentLanguage]) {
    const validation = validateLanguageResources(
      currentLanguage,
      resources[currentLanguage]
    );
    if (!validation.isValid) {
      errors.push(
        `Current language resources are incomplete: missing ${validation.missingKeys.join(', ')}`
      );
    }
    if (validation.warnings.length > 0) {
      recommendations.push(
        `Address language warnings: ${validation.warnings.join(', ')}`
      );
    }
  }

  return {
    currentLanguage,
    availableLanguages,
    loadedResources,
    errors,
    recommendations,
  };
}
